//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
namespace DotNetNuke.Modules.Admin.Modules
{
	partial class Import : Entities.Modules.PortalModuleBase
	{
		private new int ModuleId = -1;
		private ModuleInfo _Module;
		private ModuleInfo Module {
			get {
				if (_Module == null) {
					_Module = new ModuleController().GetModule(ModuleId, TabId, false);
				}
				return _Module;
			}
		}
		protected override void  OnInit(EventArgs e)
		{
 			 base.OnInit(e);

			if (Request.QueryString["moduleid"] != null) {
				Int32.TryParse(Request.QueryString["moduleid"], out ModuleId);
			}

			if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "IMPORT", Module)) {
				Response.Redirect(Common.Globals.AccessDeniedURL(), true);
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cboFolders.SelectedIndexChanged += new EventHandler(cboFolders_SelectedIndexChanged);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
			cmdImport.Click += new EventHandler(cmdImport_Click);

			try {
				if (!Page.IsPostBack) {
					cboFolders.Items.Insert(0, new ListItem("<" + Services.Localization.Localization.GetString("None_Specified") + ">", "-"));
                    ArrayList folders = FileSystemUtils.GetFoldersByUser(PortalId, false, false, "BROWSE, ADD");
					foreach (FolderInfo folder in folders) {
						ListItem FolderItem = new ListItem();
						if (folder.FolderPath == Null.NullString) {
							FolderItem.Text = Localization.GetString("Root", this.LocalResourceFile);
						} else {
                            FolderItem.Text = folder.DisplayPath;
						}
						FolderItem.Value = folder.FolderPath;
						cboFolders.Items.Add(FolderItem);
					}
				}
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cboFolders_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			cboFiles.Items.Clear();
			if (cboFolders.SelectedIndex != 0) {
				if (Module != null) {
					ArrayList arrFiles = Common.Globals.GetFileList(PortalId, "xml", false, cboFolders.SelectedItem.Value);
					foreach (FileItem objFile in arrFiles) {
						if (objFile.Text.IndexOf("content." + Common.Globals.CleanName(Module.DesktopModule.ModuleName) + ".") != -1) {
							cboFiles.Items.Add(new ListItem(objFile.Text.Replace("content." + Common.Globals.CleanName(Module.DesktopModule.ModuleName) + ".", ""), objFile.Text));
						}
						if (Common.Globals.CleanName(Module.DesktopModule.ModuleName) != Common.Globals.CleanName(Module.DesktopModule.FriendlyName))
						{
							if (objFile.Text.IndexOf("content." + Common.Globals.CleanName(Module.DesktopModule.FriendlyName) + ".") != -1)
							{
								cboFiles.Items.Add(new ListItem(objFile.Text.Replace("content." + Common.Globals.CleanName(Module.DesktopModule.FriendlyName) + ".", ""), objFile.Text));
							}
						}
					}
				}
			}
		}
		private void cmdCancel_Click(object sender, EventArgs e)
		{
			try {
				Response.Redirect(Common.Globals.NavigateURL(), true);
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdImport_Click(object sender, EventArgs e)
		{
			try {
				if (cboFiles.SelectedItem != null) {
					if (Module != null) {
						string strMessage = ImportModule(ModuleId, cboFiles.SelectedItem.Value, cboFolders.SelectedItem.Value);
						if (String.IsNullOrEmpty(strMessage)) {
							Response.Redirect(Common.Globals.NavigateURL(), true);
						} else {
							UI.Skins.Skin.AddModuleMessage(this, strMessage, UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
						}
					}
				} else {
					UI.Skins.Skin.AddModuleMessage(this, "Please specify the file to import", UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				}
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private string ImportModule(int ModuleId, string FileName, string Folder)
		{
			string strMessage = "";
			if (Module != null) {
				if (FileName.IndexOf("." + Common.Globals.CleanName(Module.DesktopModule.ModuleName) + ".") != -1 || FileName.IndexOf("." + Common.Globals.CleanName(Module.DesktopModule.FriendlyName) + ".") != -1)
				{
					if (!String.IsNullOrEmpty(Module.DesktopModule.BusinessControllerClass) && Module.DesktopModule.IsPortable) {
						try {
							object objObject = Framework.Reflection.CreateObject(Module.DesktopModule.BusinessControllerClass, Module.DesktopModule.BusinessControllerClass);
							if (objObject is IPortable) {
								StreamReader objStreamReader;
								objStreamReader = File.OpenText(PortalSettings.HomeDirectoryMapPath + Folder + FileName);
								string Content = objStreamReader.ReadToEnd();
								objStreamReader.Close();
								XmlDocument xmlDoc = new XmlDocument();
								try {
									xmlDoc.LoadXml(Content);
								} catch {
									strMessage = Localization.GetString("NotValidXml", this.LocalResourceFile);
								}
								if (String.IsNullOrEmpty(strMessage)) {
									string strType = xmlDoc.DocumentElement.GetAttribute("type").ToString();
									if (strType == Common.Globals.CleanName(Module.DesktopModule.ModuleName) || strType == Common.Globals.CleanName(Module.DesktopModule.FriendlyName))
									{
										string strVersion = xmlDoc.DocumentElement.GetAttribute("version").ToString();
										((IPortable)objObject).ImportModule(ModuleId, xmlDoc.DocumentElement.InnerXml, strVersion, UserInfo.UserID);
										Response.Redirect(Common.Globals.NavigateURL(), true);
									} else {
										strMessage = Localization.GetString("NotCorrectType", this.LocalResourceFile);
									}
								}
							} else {
								strMessage = Localization.GetString("ImportNotSupported", this.LocalResourceFile);
							}
						} catch {
							strMessage = Localization.GetString("Error", this.LocalResourceFile);
						}
					} else {
						strMessage = Localization.GetString("ImportNotSupported", this.LocalResourceFile);
					}
				} else {
					strMessage = Localization.GetString("NotCorrectType", this.LocalResourceFile);
				}
			}
			return strMessage;
		}
	}
}
